import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:family_app/src/features/secure_vault/models/vault_item_model.dart';
import 'package:family_app/src/theme/app_theme.dart';

/// 私密信息详情组件
class VaultItemDetail extends StatelessWidget {
  final VaultItemModel item;
  final VoidCallback onEdit;
  final VoidCallback onDelete;

  const VaultItemDetail({
    Key? key,
    required this.item,
    required this.onEdit,
    required this.onDelete,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(16.r),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 顶部标题栏
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Icon(item.type.icon, color: AppTheme.primaryColor),
                  SizedBox(width: 8.w),
                  Text(
                    item.title,
                    style: TextStyle(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
              Row(
                children: [
                  IconButton(
                    icon: const Icon(Icons.edit, color: AppTheme.primaryColor),
                    onPressed: onEdit,
                  ),
                  IconButton(
                    icon: const Icon(Icons.delete, color: Colors.red),
                    onPressed: onDelete,
                  ),
                ],
              ),
            ],
          ),
          Divider(height: 24.h),

          // 信息详情
          _buildDetailItem(context, '用户名/账号', item.username),
          _buildPasswordItem(context, '密码', item.password),

          // 网址（如果有）
          if (item.url != null && item.url!.isNotEmpty)
            _buildUrlItem(context, '网址', item.url!),

          // 备注（如果有）
          if (item.notes != null && item.notes!.isNotEmpty)
            _buildDetailItem(context, '备注', item.notes!),

          // 创建和更新时间
          SizedBox(height: 16.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '创建于: ${_formatDate(item.createdAt)}',
                style: TextStyle(fontSize: 12.sp, color: Colors.grey),
              ),
              Text(
                '更新于: ${_formatDate(item.updatedAt)}',
                style: TextStyle(fontSize: 12.sp, color: Colors.grey),
              ),
            ],
          ),
          SizedBox(height: 16.h),
        ],
      ),
    );
  }

  /// 构建详情项
  Widget _buildDetailItem(BuildContext context, String label, String value) {
    return Padding(
      padding: EdgeInsets.only(bottom: 16.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            label,
            style: TextStyle(
              fontSize: 14.sp,
              color: AppTheme.textSecondaryColor,
            ),
          ),
          SizedBox(height: 4.h),
          Row(
            children: [
              Expanded(
                child: Text(
                  value,
                  style: TextStyle(fontSize: 16.sp),
                ),
              ),
              IconButton(
                icon: const Icon(Icons.copy, size: 20),
                onPressed: () => _copyToClipboard(context, value),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建密码项
  Widget _buildPasswordItem(BuildContext context, String label, String value) {
    return StatefulBuilder(
      builder: (context, setState) {
        bool obscureText = true;

        return Padding(
          padding: EdgeInsets.only(bottom: 16.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                label,
                style: TextStyle(
                  fontSize: 14.sp,
                  color: AppTheme.textSecondaryColor,
                ),
              ),
              SizedBox(height: 4.h),
              Row(
                children: [
                  Expanded(
                    child: Text(
                      obscureText ? '••••••••' : value,
                      style: TextStyle(fontSize: 16.sp),
                    ),
                  ),
                  IconButton(
                    icon: Icon(
                      obscureText ? Icons.visibility : Icons.visibility_off,
                      size: 20,
                    ),
                    onPressed: () {
                      setState(() {
                        obscureText = !obscureText;
                      });
                    },
                  ),
                  IconButton(
                    icon: const Icon(Icons.copy, size: 20),
                    onPressed: () => _copyToClipboard(context, value),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  /// 构建URL项
  Widget _buildUrlItem(BuildContext context, String label, String value) {
    return Padding(
      padding: EdgeInsets.only(bottom: 16.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            label,
            style: TextStyle(
              fontSize: 14.sp,
              color: AppTheme.textSecondaryColor,
            ),
          ),
          SizedBox(height: 4.h),
          Row(
            children: [
              Expanded(
                child: InkWell(
                  onTap: () => _launchUrl(context, value),
                  child: Text(
                    value,
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.blue,
                      decoration: TextDecoration.underline,
                    ),
                  ),
                ),
              ),
              IconButton(
                icon: const Icon(Icons.open_in_new, size: 20),
                onPressed: () => _launchUrl(context, value),
              ),
              IconButton(
                icon: const Icon(Icons.copy, size: 20),
                onPressed: () => _copyToClipboard(context, value),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 复制到剪贴板
  void _copyToClipboard(BuildContext context, String text) {
    Clipboard.setData(ClipboardData(text: text));
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('已复制到剪贴板')),
    );
  }

  /// 打开URL
  Future<void> _launchUrl(BuildContext context, String urlString) async {
    try {
      final Uri url = Uri.parse(urlString);
      if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
        throw Exception('无法打开 $urlString');
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('无法打开链接: $urlString')),
      );
    }
  }

  /// 格式化日期
  String _formatDate(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')}';
  }
}
